package com.eascs.archive.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.service.ICreditArchiveService;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.dao.ArchiveCreditDao;
import com.eascs.archive.entity.CreditArchiveRecordEntity;
import com.eascs.common.util.StringUtil;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.WFRequestParam;

@Service("localCreditArchiveService")
public class CreditArchiveServiceImpl implements ICreditArchiveService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private final static String PROCESS_TYPE = "CREDIT_ARCHIVE";

	@Reference
	WorkFlowService workFlowService;

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	@Autowired
	private ArchiveCreditDao archiveDao;

	@Value("${o2o.admin.creditAchive}")
	private String creditAchive;

	/**
	 * 启动征信归档流程
	 */
	public ModelResult<Boolean> startup() {
		// 1.查询借款征信数据，入库并启动流程
		List<Object[]> orderList = archiveDao.getCreditFinishOrder();
		creditArchiveAndStartupWorkflow(orderList, 0);
		// 2.查询借款配偶征信数据，入库并启动流程
		orderList = archiveDao.getCreditFinishOrderForSpouse();
		creditArchiveAndStartupWorkflow(orderList, 1);
		// 3.查询担保人征信数据，入库并启动流程
		orderList = archiveDao.getCreditFinishOrderForSurety();
		creditArchiveAndStartupWorkflow(orderList, 2);

		return new ModelResult<Boolean>().withModel(true);
	}

	private boolean dateBefore20170301(Date date) {
		if (date == null) {
			return true;
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date endpoint = df.parse("2017-03-01 00:00:00");
			if (date.before(endpoint)) {
				return true;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 启动归档入库流程并入库 3.1号以前的数据只归档,不启动流程
	 *
	 * @param credits
	 */
	private void creditArchiveAndStartupWorkflow(List<Object[]> credits, Integer customerType) {
		for (Object[] order : credits) {
			String billCode = (String) order[0];
			String loanapplyNo = (String) order[1];
			String customerId = (String) order[2];
			String customerName = (String) order[3];
			Date creditTime = (Date) order[6];

			O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNo);
			if (StringUtil.isBlank(customerId))
				customerId = loan.getLoanId();
			if (StringUtil.isBlank(customerId))
				continue;

			O2oLoanUserEntity user = o2oLoanapplyService.fingByloanId(customerId);
			if (StringUtil.isBlank(customerId))
				customerName = user.getCustomerName();

			CreditArchiveRecordEntity creditArchiveRecordEntity = null;
			// 1.查询是否已经归档,归档数据不处理
			CreditArchiveRecordEntity entity1 = archiveDao.queryCreditArchiveRecord(loanapplyNo, billCode, customerId);
			if (entity1 != null && ("Y").equals(entity1.getIsStart())) {
				continue;
			}

			if (entity1 != null) {// 2.插入数据但是未启动流程
				creditArchiveRecordEntity = entity1;
			} else {// 2.未插入数据
				CreditArchiveRecordEntity entity = new CreditArchiveRecordEntity();
				entity.setCustomerType(customerType);
				entity.setCustomerId(customerId);
				entity.setCustomerName(customerName);
				entity.setBillCode(billCode);
				entity.setLoanapplyNo(loanapplyNo);
				entity.setCreater("系统管理员");
				entity.setCreditTime(creditTime);
				if (user != null) {
					entity.setIdCard(user.getDocumentNo());
				} else {
					logger.info("BillCode:[{}],用户表查询不到该用户LoanId：[{}]", billCode, customerId);
				}
				boolean flag = dateBefore20170301(creditTime);
				if (flag) {
					entity.setStatus(StatusContexts.ZXGD_CLO);// 3.1号以前的数据只归档
					entity.setWfStatus(StatusContexts.ZXGD_CLO);
					entity.setIsStart("Y");// 已归档
				} else {
					entity.setStatus(StatusContexts.ZXGD_NEW);//
					entity.setWfStatus(StatusContexts.ZXGD_RUN);
				}
				archiveDao.saveCreditArchive(entity);
				if (flag)
					continue;// 3.1号以前的数据只归档,不启动流程
				creditArchiveRecordEntity = entity;
			}

			WFRequestParam param = new WFRequestParam();
			param.setReferId(creditArchiveRecordEntity.getId());
			param.setReferCode(loan.getBillCode());
			param.setReferUrl(creditAchive);
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(PROCESS_TYPE);
			param.setProcessVersion("v1");
			param.setAppliedby("001");
			param.setAppliedbyName("系统管理员");
			param.setOrgNo(loan.getLtd());

			// 3.生成摘要
			O2oLoanUserEntity loanUser = o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),
					loan.getLoanId());
			String type = customerType == 0 ? "借款人" : customerType == 1 ? "配偶" : "担保人";
			String appliedDes = "征信查询人：" + loanUser.getUserFullName() + "（" + type + "）";
			param.setAppliedDes(appliedDes);
			// 摘要
			/*
			 * StringBuffer appliedDes = new StringBuffer("借款人:");
			 * appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.
			 * getLoanapplyNo(),loan.getLoanId()).getUserFullName());
			 * appliedDes.append("，申请金额:"); java.text.DecimalFormat df=new
			 * java.text.DecimalFormat("0.00"); //格式化，保留两位小数
			 * appliedDes.append(df.format(loan.getLoanaMount().doubleValue()));
			 * param.setAppliedDes(appliedDes.toString());
			 */
			logger.info("启动征信归档，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", loan.getLoanapplyNo(),
					loan.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, PROCESS_TYPE, loan.getLtd());

			// 4.启动工作流
			com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess()) {
				creditArchiveRecordEntity.setIsStart("Y");
				creditArchiveRecordEntity.setWfStatus(StatusContexts.ZXGD_RUN);
				creditArchiveRecordEntity.setStatus(StatusContexts.ZXGD_RUN);
			} else {
				creditArchiveRecordEntity.setIsStart("N");
				creditArchiveRecordEntity.setWfStatus(StatusContexts.ZXGD_NEW);
				logger.error("启动征信归档失败，贷款单号为：【{}】，错误信息{}", loanapplyNo, modelResult.getErrMsg());
			}
			archiveDao.updateById(creditArchiveRecordEntity);
		}

	}

	@Override
	public ModelResult<Boolean> startupNew() {
		// 1.查询借款征信数据，入库并启动流程
		List<Object[]> orderList = archiveDao.getNewCreditFinishOrder();
		creditNewArchiveAndStartupWorkflow(orderList);
		return new ModelResult<Boolean>().withModel(true);
	}

	// 新征信启动工作流
	private void creditNewArchiveAndStartupWorkflow(List<Object[]> credits) {
		for (Object[] order : credits) {
			try {
				String billId = (String) order[0];
				String billCode = (String) order[1];
				String customerId = (String) order[2];
				String customerName = (String) order[3];
				String documentNo = (String) order[4];
				String zxType = (String) order[5];
				Date creditTime = (Date) order[6];
				String orgNo = (String) order[7];
				// 客户类型
				int customerType = -1;
				String customerTypeDes = null;
				if (StringUtils.equals(zxType, "ZX_JKR")) {
					customerType = 0;
					customerTypeDes = "借款人";
				} else if (StringUtils.equals(zxType, "ZX_PO")) {
					customerType = 1;
					customerTypeDes = "配偶";
				} else if (StringUtils.equals(zxType, "ZX_DBR")) {
					customerType = 2;
					customerTypeDes = "担保人";
				}

				CreditArchiveRecordEntity creditArchiveRecordEntity = null;
				// 1.查询是否已经归档,归档数据不处理
				CreditArchiveRecordEntity entity1 = archiveDao.queryCreditArchiveRecord(billId, billCode, customerId);
				if (entity1 != null && ("Y").equals(entity1.getIsStart())) {
					continue;
				}

				if (entity1 != null) {// 2.插入数据但是未启动流程
					creditArchiveRecordEntity = entity1;
				} else {// 2.未插入数据
					CreditArchiveRecordEntity entity = new CreditArchiveRecordEntity();
					entity.setCustomerType(customerType);
					entity.setCustomerId(customerId);
					entity.setCustomerName(customerName);
					entity.setBillCode(billCode);
					entity.setLoanapplyNo(billId);
					entity.setCreater("系统管理员");
					entity.setCreditTime(creditTime);
					entity.setIdCard(documentNo);
					boolean flag = dateBefore20170301(creditTime);
					if (flag) {
						entity.setStatus(StatusContexts.ZXGD_CLO);// 3.1号以前的数据只归档
						entity.setWfStatus(StatusContexts.ZXGD_CLO);
						entity.setIsStart("Y");// 已归档
					} else {
						entity.setStatus(StatusContexts.ZXGD_NEW);
						entity.setWfStatus(StatusContexts.ZXGD_RUN);
					}
					archiveDao.saveCreditArchive(entity);
					if (flag) {
						continue;// 3.1号以前的数据只归档,不启动流程
					}
					creditArchiveRecordEntity = entity;
				}

				WFRequestParam param = new WFRequestParam();
				param.setReferId(creditArchiveRecordEntity.getId());
				param.setReferCode(billCode);
				param.setReferUrl(creditAchive);
				param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
				param.setProcessType(PROCESS_TYPE);
				param.setProcessVersion("v1");
				param.setAppliedby("001");
				param.setAppliedbyName("系统管理员");
				param.setOrgNo(orgNo);
				// 3.生成摘要
				String appliedDes = "征信查询人：" + customerName + "（" + customerTypeDes + "）";
				param.setAppliedDes(appliedDes);
				// 摘要
				logger.info("启动征信归档，参数有征信id：【{}】，征信编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", billId, billCode,
						ProcessTemplate.SYSTEM_MODULE_O2O, PROCESS_TYPE, orgNo);
				// 4.启动工作流
				com.eascs.workflow.common.vo.ModelResult<Boolean> modelResult = workFlowService.instance(param);
				if (modelResult.isSuccess()) {
					creditArchiveRecordEntity.setIsStart("Y");
					creditArchiveRecordEntity.setWfStatus(StatusContexts.ZXGD_RUN);
					creditArchiveRecordEntity.setStatus(StatusContexts.ZXGD_RUN);
				} else {
					creditArchiveRecordEntity.setIsStart("N");
					creditArchiveRecordEntity.setWfStatus(StatusContexts.ZXGD_NEW);
					logger.error("启动征信归档失败，征信编号为：【{}】，错误信息{}", billCode, modelResult.getErrMsg());
				}
				archiveDao.updateById(creditArchiveRecordEntity);
			} catch (Exception e) {
				logger.error("征信归档失败", e);
			}
		}
	}
}
